package cn.wizzer.app.user.modules.service.impl;

import cn.wizzer.app.user.modules.models.Banner;
import cn.wizzer.app.user.modules.services.BannerService;
import cn.wizzer.framework.base.Result;
import cn.wizzer.framework.base.service.BaseServiceImpl;
import com.alibaba.dubbo.config.annotation.Service;
import org.nutz.dao.Dao;
import org.nutz.ioc.loader.annotation.IocBean;
import org.nutz.lang.Strings;

import java.util.ArrayList;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

@IocBean(args = {"refer:dao"})
@Service(interfaceClass = BannerService.class)
public class BannerServiceImpl extends BaseServiceImpl<Banner> implements BannerService {
    public BannerServiceImpl(Dao dao) {
        super(dao);
    }

    @Override
    public Object deleteById(String id) {
        return this.delete(id) > 0 ? Result.success("删除成功"):Result.error("删除失败");
    }

    @Override
    public void updateById(Banner banner, String id) {
        this.updateById(banner,id);
    }

    private ArrayList typeList = Result.createList("PC","Phone","Crown");
    /**
     * Banner校验逻辑
     * @param banner Banner
     * @return boolean
     */
    public Result validateBanner(Banner banner) {
        // 名称校验
        if (Strings.isBlank(banner.getName())) {
            return Result.error("Banner名称不能为空");
        }
        // 类型校验
        if (!typeList.contains(banner.getType()) ) {
            return Result.error("Banner类型错误");
        }
        // 图片不能为空
        if (Strings.isBlank(banner.getPicture())) {
            return Result.error("图片不能为空");
        }
        // URL格式校验
        if (Strings.isNotBlank(banner.getHref())) {
            // url正则表达式（有没有http/https都可以，要带域名，例如hello.com/video/1231)
            String reg = "((http[s]{0,1}|ftp)://[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&amp;*+?:_/=&lt;&gt;]*)?)|((www.)|[a-zA-Z0-9\\.\\-]+\\.([a-zA-Z]{2,4})(:\\d+)?(/[a-zA-Z0-9\\.\\-~!@#$%^&amp;*+?:_/=&lt;&gt;]*)?)";
            Matcher matcher = Pattern.compile(reg).matcher(banner.getHref());
            if (!matcher.find()) {
                return Result.error("URL格式不正确");
            }
        }
        return Result.success();
    }
}
